/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import domain.Electricityconsumption;
import domain.Electricitycontract;
import domain.Invoice;
import java.sql.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

/**
 *
 * @author Alberto
 */
public class ElectricityconsumptionDao {

    EntityManager em;
    EntityTransaction tx;

    public ElectricityconsumptionDao() {
        em = SingletonDao.getInstance().getEntityManager();
        tx = SingletonDao.getTx();
    }

    public Electricityconsumption getElectricityconsumption(Integer idE){
        Electricityconsumption e = (Electricityconsumption) em.createNativeQuery("select * from electricityconsumption as e where e.idElectricityCons='"+idE+"'", Electricityconsumption.class).getSingleResult();
        return e;
    }

    public void saveElectricityconsumption(Electricityconsumption e){
        tx.begin();
        em.persist(e);
        tx.commit();
    }

    public void removeElectricityconsumption (Electricityconsumption e){
        tx.begin();
        em.remove(e);
        tx.commit();
    }

    public Electricityconsumption getElectricityconsumptionDate(Electricitycontract m){
        Electricityconsumption ec = null;
        Date date = new Date(new java.util.Date().getTime());
        int month = date.getMonth();
        int year = date.getYear()+1900;
        int day = date.getDate();
        List list = em.createNativeQuery("select * from electricityconsumption as e, contract as cont, consumption as cons where cont.idContract='"+m.getContract().getIdContract()+"' and  e.consFK=cons.idCons and cons.consFk=cont.idContract and e.dateTo>'"+year+"-"+month+"-"+day+"'", Electricityconsumption.class).getResultList();
        if(!list.isEmpty()){
            ec = (Electricityconsumption) list.get(0);
        }
        return ec;
    }

    public List<Electricityconsumption> getElectricityListConsumption(Invoice i){
        List<Electricityconsumption> l = em.createNativeQuery("select * from electricityconsumption as ec where ec.invoiceFK ='"+i.getIdInvoice()+"'", Electricityconsumption.class).getResultList();
        return l;
    }

}
